package com.jason.amber.thread;

/**
 * 线程中的生产者消费者问题
 * Created by fuyongde on 16/3/30.
 */
public class ProducerConsumer {
    public static void main(String[] args) {
        SyncStack syncStack = new SyncStack();
        Producer p = new Producer(syncStack);
        Consumer c = new Consumer(syncStack);
        new Thread(p).start();
        new Thread(c).start();
    }
}

class Wotou {

    int id;

    public Wotou(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Wotou{" +  "id=" + id + '}';
    }
}

class SyncStack {
    int index = 0;
    Wotou[] array = new Wotou[6];

    public synchronized void push(Wotou wotou) {
        if (index == array.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        array[index] = wotou;
        index ++;
    }

    public synchronized Wotou pop() {
        if (index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        index --;
        return array[index];
    }
}

class Producer implements Runnable {

    SyncStack syncStack = null;

    public Producer(SyncStack syncStack) {
        this.syncStack = syncStack;
    }

    public void run() {
        for (int i = 0; i < 20; i++) {
            Wotou wotou = new Wotou(i);
            syncStack.push(wotou);
            System.out.println("生产了" + wotou);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {

    SyncStack syncStack = null;

    public Consumer(SyncStack syncStack) {
        this.syncStack = syncStack;
    }

    public void run() {
        for (int i = 0; i < 20; i++) {
            Wotou wt = syncStack.pop();
            System.out.println("消费了" + wt);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}